package com.lizhe.exception.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lizhe.exception.model.AjaxResponse;
import com.lizhe.exception.model.Article;
import com.lizhe.exception.service.ArticleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 类描述: 增删改查
 *
 * @author Lz on 2021-10-28
 */
@RestController
@RequestMapping("/rest")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @GetMapping("/findOne")
    public AjaxResponse findOne(Integer id) {
        return AjaxResponse.success(articleService.selectByPrimaryKey(id));
    }

    @PostMapping("/save")
    public AjaxResponse save(@RequestBody Article article) {
        return AjaxResponse.success(articleService.insert(article));
    }

    //使用pageHelper分页
    @PostMapping("/list")
    public AjaxResponse list(@RequestBody Article article) {

        // 只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页!!!!
        PageHelper.startPage(1,2);
        List<Article> articles = articleService.findByAll(article);
        PageInfo<Article> pageInfo = PageInfo.of(articles);

        long total = pageInfo.getTotal();
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("list",articles);
        resultMap.put("total",total);
        return AjaxResponse.success(resultMap);
    }

    @PostMapping("/updateOne")
    public AjaxResponse updateOne(@RequestBody Article article) {
        return AjaxResponse.success(articleService.updateByPrimaryKeySelective(article));
    }
}
